/**
 * Filename: AgreementAdapter.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/3/12 14:11
 */
package com.github.postsanf.yinian.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNAgreeItem;

import java.util.List;

public class AgreementAdapter extends RecyclerView.Adapter<AgreementAdapter.ViewHolder>{
	public static final int TYPE_HEADER = 0;
	public static final int TYPE_NORMAL = 1;
	private List<YNAgreeItem> mDatas;
	private View mHeaderView;

	public AgreementAdapter(List<YNAgreeItem> mDatas)
	{
		this.mDatas = mDatas;
	}

	public  class ViewHolder extends RecyclerView.ViewHolder {
		TextView 		agree_item_title;
		TextView		agree_item_content;

		public ViewHolder(View itemView) {
			super(itemView);
			if(itemView == mHeaderView) return;

			agree_item_title = (TextView) itemView
						.findViewById(R.id.agree_item_title);
			agree_item_content = (TextView) itemView
						.findViewById(R.id.agree_item_content);
		}

		public void bindData(final YNAgreeItem listItems)
		{
			if (listItems != null)
			{
				agree_item_title.setText(listItems.getTitle());
				agree_item_content.setText(listItems.getContent());
			}
		}
	}

	public void setHeaderView(View headerView) {
		mHeaderView = headerView;
		notifyItemInserted(0);
	}
	public View getHeaderView() {
		return mHeaderView;
	}

	@Override
	public int getItemViewType(int position) {
		if(mHeaderView == null) return TYPE_NORMAL;
		if(position == 0) return TYPE_HEADER;
		return TYPE_NORMAL;
	}

	private YNAgreeItem getItem(int position) {
		return mDatas.get(position);
	}

	// 创建ViewHolder
	@Override
	public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		if(mHeaderView != null && viewType == TYPE_HEADER) return new ViewHolder(mHeaderView);
		View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_agree_item , parent, false);
		return new ViewHolder(convertView);
	}

	// 绑定数据到View
	@Override
	public void onBindViewHolder(ViewHolder holder, int position) {
		if(getItemViewType(position) == TYPE_HEADER) return;
		final int pos = getRealPosition(holder);
		YNAgreeItem listItems = getItem(pos);
		holder.bindData(listItems);
		holder.itemView.setTag(listItems);
	}

	public int getRealPosition(RecyclerView.ViewHolder holder) {
		int position = holder.getLayoutPosition();
		return mHeaderView == null ? position : position - 1;
	}

	@Override
	public int getItemCount() {
		return mHeaderView == null ? mDatas.size() : mDatas.size() + 1;
	}
}
